# -*- coding: utf-8 -*-
"""
@Author: Logan
@Date:   2025/7/14 16:33
@Description:
钉钉文档地址:https://open.dingtalk.com/document/group/custom-robot-access#title-72m-8ag-pqw
"""
import time

import requests

from common.tools import get_every_wallpaper
from config.yaml_config import GetConf


def send_dingtalk_msg(webhook, content):
    """
    发送钉钉的消息-text
    Args:
        webhook:
        content: 具体的发送文字内容

    Returns:

    """
    headers = {"Content-Type": "application/json ;charset=utf-8 "}

    data = {
        "msgtype": "text",
        "text": {"content": content, "at": {"isAtAll": False}},
    }
    res = requests.post(url=webhook, json=data, headers=headers)
    print("发送钉钉消息，返回结果:", res.text)


def send_dingtalk_msg_markdown(
        ding_webhook,
        allure_url,
        total_count,
        success_count,
        fail_count,
        failed_testcases_name,
        report_title,
):
    """
    发送markdown格式的消息到钉钉
    :param ding_webhook: 钉钉群的webhook
    :param allure_url:allure地址
    :param total_count: 总数
    :param success_count:成功个数
    :param fail_count:失败个数
    :param failed_testcases_name:失败的用例名称
    :param report_title: 报告标题
    :return:
    """
    # 获取壁纸
    wallpaper_url = get_every_wallpaper()

    headers = {"Content-Type": "application/json ;charset=utf-8 "}
    if fail_count == 0:
        failed_testcases_name = ""
    # 美化后的消息数据
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title": report_title,
            "text": (
                f"# 📋 {report_title}\n"
                f"> 测试结束时间：{time.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
                f"## 📊 测试概览\n"
                f"| 用例总数 | ✅ 通过 | ❌ 失败 |\n"
                f"|----------|---------|---------|\n"
                f"| {total_count} | {success_count} | {fail_count} |\n\n"
                f"## 📝 测试结果\n"
                f"> 本次测试共执行 {total_count} 个用例，通过率 {success_count / total_count * 100:.1f}%\n\n"
                f"{f'## ❗ 失败用例详情\n{failed_testcases_name}\n\n' if int(fail_count) > 0 else '## ✨ 全部通过\n🎉 本次测试无失败用例！\n\n'}"
                f"## 🖼️ 今日壁纸\n"
                f"![测试激励图]({wallpaper_url})\n\n"
                f"## 📊 查看报告\n"
                f"[🚀 点击访问 Allure 报告]({allure_url})\n"
                f"###### 测试人员:Logan"
            ),
            "at": {
                "isAtAll": int(fail_count) > 0  # 失败时@全员
            }
        }
    }
    res = requests.post(url=ding_webhook, json=data, headers=headers)
    print("发送钉钉消息，返回结果:", res.text)


if __name__ == '__main__':
    webhook = GetConf().get_dingding_webhook()
    send_dingtalk_msg(webhook, "william测试")
